
import {lzGetFileSize} from "./file.js"
import guid from "./guid.js"
//#ifdef APP-PLUS
let gdQuantum=null
if(uni.$u.os()!='ios'){
	gdQuantum = uni.requireNativePlugin('gdQuantum');
}
//#endif
let {deviceId}=uni.getSystemInfoSync();
let uuid=guid()
/**
 * 初始化数据
 * @param deviceSn {string }
 * @param  imei {string}  
 * @param  phoneNum {string}  
 **/
function init() {
	return new Promise((resolve, reject)=>{
		gdQuantum.init(uuid,deviceId,'',function(data){
			if(data.method=='onInit'){
				let item=JSON.parse(data.content)
				if(item.result==-3){
					reject(item)
				}
			}
			//初始化完成
			if(data.method=='onPlatformAuth'){
				let item=JSON.parse(data.content)
				if(item.result==0){
					//console.log('初始化完成');
					resolve(item)
				}else{
					reject()
				}
			}else if(data.method=='alreadyInit'){//已经初始化过了
				//console.log('已经初始化过了');
				resolve()
			}
		})
	})
	
}
/**
 * 解密
 * @param key {string 秘钥}
 * @param  str {string 密文}  
 **/
async function decrypt(key,str) {
	//先判断秘钥使用量是否达到阈值
	let onoff= await thresholdRemind()
	if(onoff.code==-1){
		return onoff
	}
	return new Promise(async (resolve, reject) => {
		if(onoff.code==0&&onoff.data==true){
			uni.showModal({
				title: '提示',
				content: `秘钥使用量已达到指定阈值${getApp().globalData.GD_QSS.threshold}%,请及时充值`,
				showCancel: false,
				confirmText: '确定',
				success: async res => {
					if(res.confirm){
						let stream= await get(str)
						gdDecrypt(key,stream).then(resuls=>{
							let req={
								code:0,
								data:'data:image/jpg;base64,'+resuls
							}
							resolve(req)
						}).catch(err=>{
							reject(err)
						})
					}
				},
				fail: () => {},
				complete: () => {}
			});
		}else if(onoff.code==0&&onoff.data==false){
			let stream= await get(str)
			gdDecrypt(key,stream).then(resuls=>{
				let req={
					code:0,
					data:'data:image/jpg;base64,'+resuls
				}
				resolve(req)
			}).catch(err=>{
				//console.log('解密失败：',err);
				reject(err)
			})
		}
	})
}

async function gdDecrypt(key,str){
	return new Promise((resolve, reject) => {
		init().then((res)=>{
			let data = gdQuantum.decryptByKey(key,str)
			resolve(data)
		}).catch((err)=>{
			//console.log('初始化失败：',err);
			reject(err)
		})
	})
}
/**
 * 获取秘钥详情
 **/
function getSecretKeyInfo(key,str) {
	return new Promise((resolve, reject) => {
		init().then((res)=>{
			//剩余 单位字节
			let surplus=gdQuantum.getKeyRemainder()
			//已消耗
			let consume=gdQuantum.getKeyConsume()
			//总密钥量
			let total=gdQuantum.getKeyTotal()
			//消耗百分比
			let percentage=total!=0? 100- Math.floor(surplus/total * 100):0
			surplus=lzGetFileSize(surplus)
			consume=lzGetFileSize(consume)
			total=lzGetFileSize(total)
			resolve({
				surplus,
				consume,
				total,
				percentage
			})
		}).catch(err=>{
			//console.log('获取秘钥详情失败',err);
			resolve(err)
		})
	})
}
//是否达到用户设置的指定阈值并是否需要提醒
//返回值为true需要提醒用户
async function thresholdRemind(){
	let data= await getSecretKeyInfo()
	if(data.percentage){
		if(getApp().globalData.GD_QSS.remind && (data.percentage>getApp().globalData.GD_QSS.threshold||data.percentage==getApp().globalData.GD_QSS.threshold)){//用户设置了阈值提醒
			return {
				code:0,
				data:true
			}
		}else{
			return {
				code:0,
				data:false
			}
		}
	}else{
		return {
			code:-1,
			data
		}
	}
	
}
async function get(url){
	return new Promise((resolve, reject) => {
		uni.request({
		    url,
		    success: (res) => {
				resolve(res.data)
		    },
			fail(err) {
				//console.log(err);
			}
		});
	})
}

export default {
	init,
	decrypt,
	getSecretKeyInfo,
	thresholdRemind
}
